package com.example.itcast.service;

import com.example.itcast.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IpCountService {
    private Map<String, Integer> ipCountMap = new HashMap<String, Integer>();

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 记录ip访问次数
     */
    public void count(){
        //获取当前操作ip
        String ip = httpServletRequest.getRemoteAddr();
        //根据ip地址从Map中取值
        Integer count = ipCountMap.get(ip);
        if(count == null){
            ipCountMap.put(ip, 1);
        }else {
            ipCountMap.put(ip, count+1);
        }
    }
    @Autowired
    private IpProperties ipProperties;

    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print(){
        if(ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())){
            System.out.println("         IP访问监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println(String.format("|%18s  |%5d  |",key,value));
            }
            System.out.println("+--------------------+-------+");
        }else if(ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())){
            System.out.println("     IP访问监控");
            System.out.println("+-----ip-address-----+");
            for (String key: ipCountMap.keySet()) {
                System.out.println(String.format("|%18s  |",key));
            }
            System.out.println("+--------------------+");
        }

        if(ipProperties.getCycleReset()){
            ipCountMap.clear();
        }
    }
    public static void main(String[] args) {
        new IpCountService().print();
    }


}
